package zcy.stackAndQueue;

import java.util.Stack;

/**
 * 如何仅用一个递归函数和栈操作逆序实现一个栈
 * Created by hpp on 2017/9/28.
 */
public class ReverseStack {

    /**
     * 思路，需要设计出两个递归函数
     * 递归函数一：将栈stack的栈底元素返回并移除getAndRemoveLastElement
     * 递归函数二：逆序一个栈
     */
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
//        getAndRemoveLastElement(stack);
        System.out.println(getAndRemoveLastElement(stack));
    }

    public static int getAndRemoveLastElement(Stack<Integer> stack) {
        int result = stack.pop();
        if (stack.isEmpty()) {
            return result;
        } else {
            int last = getAndRemoveLastElement(stack);
            stack.push(result);
            return last;
        }
    }

    public static void reverse(Stack<Integer> stack) {
        if (stack.isEmpty()) {
            return;
        }
        int i = getAndRemoveLastElement(stack);
        reverse(stack);
        stack.push(i);
    }


}
